<?php
class ControllerToolOtherOrders extends Controller {
    public function index() {
        if ($this->session->data['ret']) {
            if (true === $this->session->data['ret']['status']) {
                $data['success'] = $this->session->data['ret']['message'];
            }else{
                $data['error_warning'] = $this->session->data['ret']['message'];
            }
            unset($this->session->data['ret']);
        }

        $data['post_max_size'] = $this->_returnBytes( ini_get('post_max_size') );
        $data['upload_max_filesize'] = $this->_returnBytes( ini_get('upload_max_filesize') );
        $data['action'] = $this->url->link('tool/other_orders/importExcel', 'token=' . $this->session->data['token'], 'SSL');

        $data['breadcrumbs'] = array(
            array(
                'text'      => '首页',
                'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
                'separator' => false,
            ),
            array(
                'text'      => '外场订单导入',
                'href'      => $this->url->link('tool/other_orders', 'token=' . $this->session->data['token'], 'SSL'),
                'separator' => ' :: '
            ),
        );

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('tool/other_orders.tpl', $data));
    }

    /*
     * excel导入主函数，保存到本地，记录导入日志，返回最终结果
     */
    public function importExcel() {
        if(($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->_validate())) {
            if ('po' == $this->request->post['uploadType']) {
                $uploadType = 'po';
                $secParam = false;
            }else if ('order' == $this->request->post['uploadType']){
                $uploadType = 'order';
                $secParam['importPrice'] = $this->request->post['importPrice'];
				$secParam['importStock'] = $this->request->post['importStock'];
            }
            //$uploadType = ('po' == $this->request->post['uploadType']) ? 'po' : 'order';
            $dateAdded = date('Ymd');
            $fileUnique = md5(file_get_contents($this->request->files['upload']['tmp_name']));
            $fileExt = pathinfo($this->request->files['upload']['name'], PATHINFO_EXTENSION);
            $this->load->model('tool/other_orders');
            $excelUploadLogId = $this->model_tool_other_orders->addNew($fileUnique, $uploadType);
            @mkdir(DIR_APPLICATION.'excelUpload/OO_'.$dateAdded, 0777, true);
            $localFilePath = DIR_APPLICATION.'excelUpload/OO_'.$dateAdded.'/'.$fileUnique.'_'.$excelUploadLogId.'.'.$fileExt;
            if ((isset( $this->request->files['upload'] )) && (is_uploaded_file($this->request->files['upload']['tmp_name']))) {
                if (false === move_uploaded_file($this->request->files['upload']['tmp_name'], $localFilePath)) {
                    $ret = array(
                        'status' => false,
                        'message' => '上传文件失败，请检查文件大小 ！',
                    );
                }else{
                    $ret = $this->{'importInto'.ucfirst($uploadType)}($localFilePath, $secParam);
                }
            }else{
                $ret = array(
                    'status' => false,
                    'message' => '上传文件不能为空 ！',
                );
            }
            if (!$ret['status']) {
                $this->model_tool_other_orders->importFailed($excelUploadLogId);
            }
        }else{
            $ret = array(
                'status' => false,
                'message' => '没有操作权限 ！',
            );
        }
        $this->session->data['ret'] = $ret;
        $this->response->redirect($this->url->link('tool/other_orders', 'token=' . $this->session->data['token'], 'SSL'));
        //$this->response->addHeader('Content-Type: application/json');
        //$this->response->setOutput(json_encode($ret));
    }

    /*
     * excel导入到采购单和入库单
     * @param $localFilePath 服务器端保存的excel文件路径
     */
    protected function importIntoPo ($localFilePath, $secParam=false){

    
        $this->load->library('PHPExcel/PHPExcel');
        $savePath = $localFilePath;
        $PHPExcel = new PHPExcel();
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($savePath)){
        $PHPReader = new PHPExcel_Reader_Excel5();
        }
        $PHPExcel = $PHPReader->load($savePath);
        $currentSheet = $PHPExcel->getSheet(0);
        $allRow = $currentSheet->getHighestRow();
        // var_dump($allRow);
        //获取order_product_id, express_name, express_number在excel中的index
        $order_idx = $unique_idx = $pcode_idx = $pro_name_idx = $qty_idx = $price_idx = $create_idx = 0;
        $tmp_idx = 'A'; //假设导入表格不会长于Z
        $currentRow = 1;
        $pcode_idx ='D';
        $qty_idx ='F';
        $create_idx ='H';
        if (!$json) {
        $this->load->model('sale/purchase_order');
        $products_info = array();
        // var_dump($allRow);
        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
          $pcode = (String)$currentSheet->getCell($pcode_idx.$currentRow)->getValue();
          $qty = (String)$currentSheet->getCell($qty_idx.$currentRow)->getValue();
          $qty = round ($qty,0);
          $create = (String)$currentSheet->getCell($create_idx.$currentRow)->getValue();
          $create = ($create-25569)*24*60*60; 
          $strlen = strlen($pcode);
          $time =time();
        // var_dump($time);
        // if ((int)$create<$time) {
            // var_dump($create);
            $time = date('Y-m-d H:i:s',$create); 
        // }
          // var_dump($time);die();

          // var_dump($pcode);
          // var_dump($strlen);
            if ($strlen==11) {
                $pcode = substr($pcode, 0, 10);
            }elseif ($strlen==10) {
                $pcode = $pcode;
            }else{
                $json['message'] = '第' . $currentRow . '行商品编码对应商品未找到';
            }
          // var_dump($pcode);
          // var_dump($qty);
          // die();
          //检查product_code是否存在

          $product = M('product')->where(array('product_code' => $pcode))->find();
          // echo M('product')->getlastsql();die()
          // var_dump($product);die();
          if(empty($product['product_id'])) {
            $json['message'] = '第' . $currentRow . '行商品编码对应商品未找到';
          }

          if(empty($qty)) {
            continue;
          }
          if(isset($json['message'])) {
            return array(
                'status' => false,//导入结果，boolean，标记成功失败
                'message' => $json['message'],//返回信息
             );
          }
       
          $pcodechild = substr($product['product_code'], 0, 10).substr($time, 0, 7);


          if ($product['product_type']==1) {
              $product_data[$pcodechild]['product_id'] = $product['product_id'];
              $product_data[$pcodechild]['product_code'] = $product['product_code'];
              $product_data[$pcodechild]['time'] = substr($time, 0, 7);
              $product_data[$pcodechild]['qty'] += $qty;
          }elseif ($product['product_type']==2) {
              $product_datag[$pcodechild]['product_id'] = $product['product_id'];
              $product_datag[$pcodechild]['product_code'] = $product['product_code'];
              $product_datag[$pcodechild]['time'] = substr($time, 0, 7);
              $product_datag[$pcodechild]['qty'] += $qty;
          }
        }        

        }
        // die();
        // var_dump($product_datag);
        //整合组合商品
        foreach ($product_datag as $key => $value) {
            // var_dump($value);
        $child_pcodes = $this->model_tool_other_orders->getpro($value['product_code']);
            // var_dump($child_pcodes);
            foreach ($child_pcodes as $key => $value1) {
                $pcodechild = substr($value1['child_product_code'], 0, 10).substr($value['time'], 0, 7);
                // var_dump( $pcodechild);die();

                $product_data[$pcodechild]['product_code']=$value['product_code'];
                $product_data[$pcodechild]['time']=substr($value['time'], 0, 7);
                $product_data[$pcodechild]['product_id']=$value1['child_product_id'];
                $product_data[$pcodechild]['qty']+=$value['qty']*$value1['child_quantity'];
            }
        }
        // die();
        //整合供应商
        // var_dump($product_data);die();

        $child_pcodes = $this->model_tool_other_orders->getProvendor($product_data,$time);

        return array(
            'status' => true,//导入结果，boolean，标记成功失败
            'message' => $json['message'],//返回信息
        );
 
    }

    /*
     * excel导入到订单和出库单
     * @param $localFilePath 服务器端保存的excel文件路径
     */
    protected function importIntoOrder ($localFilePath, $check){

		$this->load->model('tool/saleimport');

		$result = $this->model_tool_saleimport->uploadOrder($localFilePath,$check);
		
		if($result){
			return array(
				'status' => true,//导入结果，boolean，标记成功失败
				'message' => '导入成功',//返回信息
			);
		}
		else{
			return array(
				'status' => false,//导入结果，boolean，标记成功失败
				'message' => '导入失败',//返回信息
			);
		}

    }

    protected function _returnBytes($val) {
        $val = trim($val);
        switch (strtolower(substr($val, -1))) {
            case 'm': $val = (int)substr($val, 0, -1) * 1048576; break;
            case 'k': $val = (int)substr($val, 0, -1) * 1024; break;
            case 'g': $val = (int)substr($val, 0, -1) * 1073741824; break;
            case 'b':
                switch (strtolower(substr($val, -2, 1))) {
                    case 'm': $val = (int)substr($val, 0, -2) * 1048576; break;
                    case 'k': $val = (int)substr($val, 0, -2) * 1024; break;
                    case 'g': $val = (int)substr($val, 0, -2) * 1073741824; break;
                    default : break;
                } break;
            default: break;
        }
        return $val;
    }

    private function _validate() {
        if (!$this->user->hasPermission('modify', 'tool/other_orders')) {
            $this->error['warning'] = $this->language->get('警告: 无权限修改本插件！');
        }
        if (!$this->error) {
            return true;
        }else{
            return false;
        }
    }
}
